const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const config = require('../config/jwt_secret/secert')
const qrcode = require('qrcode')
// 用户表
const UserModel = require('../model/UserModel')

// 生成二维码接口
router.get('/create/code', (req, res) => {
    const { uuid } = req.query
    // 加上 waif_chat:// 特定前缀，当小程序端扫描不带这个前缀，则不进行跳转
    let qrcodeContent = 'waif_chat://' + jwt.sign({
        uuid
    }, config.jwtSecret, {
        expiresIn: 15 * 60 * 1 // 15分钟
    })

    // 获取二维码
    qrcode.toDataURL(qrcodeContent, {
        width: 200,
        color: {
            dark: '#4460f1'
        }
    }).then((url) => {
        // url: base64
        res.json({
            status: 200,
            msg: '二维码生成成功',
            url
        })
    }).catch(() => {
        res.json({
            status: 404,
            msg: '二维码生成失败'
        })
    })
})

// 移动端扫码登录接口
router.post('/mobile/login', async (req, res) => {
    const { _id, token } = req.body
    try {
        const user = await UserModel.findOne({ _id, token, isStatus: true }, {
            _id: 1,
            nick: 1,
            imgUrl: 1,
            sex: 1,
            birthday: 1,
            start: 1,
            sign: 1, 
            token: 1
        })
        if (!user) {
            return res.json({
                status: 402,
                msg: '账号已禁用'
            })
        }
        res.json({
            status: 200,
            msg: '扫码登录成功',
            data: user
        })
    } catch (error) {
        res.json({
            status: 404,
            msg: '服务器错误'
        })
    }
})

module.exports = router